package mysql

import (
	"bluebell/models"
	"bluebell/settings"
	"database/sql"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB
var sqlDB *sql.DB

func InitDatabase(MysqlConfig *settings.MysqlConfig) (err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local", MysqlConfig.User, MysqlConfig.Password, MysqlConfig.Host, MysqlConfig.Port, MysqlConfig.Dbname)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return
	}
	//获取获取通用数据库对象 *sql.DB
	sqlDB, err = DB.DB()
	if err != nil {
		return
	}

	//验证数据库是否建立连接,出问题返回error对象，没出问题返回nil
	if err = sqlDB.Ping(); err != nil {
		zap.L().Error("连接数据库失败", zap.String("err", err.Error()))
		return
	}
	zap.L().Info("数据库连接成功")
	return

}

//绑定数据库表
func AutoMigrate() {
	DB.AutoMigrate(&models.User{}, &models.Community{})
}

func CloseLinkedDatabase() {
	sqlDB.Close()
}
